package com.xuzz.study.io.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

public class TestServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap=new ServerBootstrap();

            //指定线程模型
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("MyHttpServerCodec",new HttpServerCodec());
                            socketChannel.pipeline().addLast("MyTestHttpHandler",new TestHttpHandler());
                        }
                    })
            ;
            ChannelFuture channelFuture = serverBootstrap.bind(6688).sync();
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess())
                    {
                        System.out.println("监听成功");
                    }
                    else
                    {
                        System.out.println("监听失败");
                    }
                    if(channelFuture.isCancelled())
                    {
                        System.out.println("取消了");
                    }
                }
            });
            channelFuture.channel().closeFuture().sync();


        }
        finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
